package com.gxz.redis.controller;

import com.gxz.redis.domain.MoneyLog;
import com.gxz.redis.redission.DistributedLocker;
import com.gxz.redis.service.MoneyLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;



/*****
 * @author guxz4
 * @Description: com.itheima.controller.MoneyLogController
 ****/
@RestController
@RequestMapping(value = "/mlog")
public class MoneyLogController {

    @Autowired
    private MoneyLogService moneyLogService;

    @Autowired
    private DistributedLocker distributedLocker;

    /****
     * 分布式锁测试
     * @return
     */
    @GetMapping(value = "/lock")
    public String lockDemo(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("进入流程！"+simpleDateFormat.format(new Date()));
        //1）获取指定锁
        String lockkey = "ITHEIMABJ";
        Boolean lock = distributedLocker.lock(lockkey, 10L, TimeUnit.SECONDS, 10L);

        if(lock){
            //2）执行操作
            System.out.println("执行操作："+simpleDateFormat.format(new Date()));
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //3）释放锁
            distributedLocker.unlock(lockkey);
            System.out.println("释放："+simpleDateFormat.format(new Date()));
        }
        return "OK";
    }

    /***
     * 抢红包列表
     */
    @GetMapping(value = "/top")
    public List<MoneyLog> top(){
        System.out.println("结束！");
//        try {
//            Thread.sleep(5000);
//            System.out.println("结束！");
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        return moneyLogService.top();
    }

    /***
     * 抢红包列表
     */
    @GetMapping(value = "/list")
    public List<MoneyLog> list(){
        List<MoneyLog> mlogs = moneyLogService.list();
        return mlogs;
    }

}
